﻿using AgencyManagerSystem.AsmType;
using AgencyManagerSystem.Common;
using AgencyManagerSystem.Core;
using AgencyManagerSystem.DataFetcher;
using AgencyManagerSystem.DataUpdater;
using AgencyManagerSystem.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace AgencyManagerSystem.Controllers
{
    public class OrderController :  MyControllerBase
    {
        OrderManager manager;
        OrderFetcher fetcher;
        OrderDetailFetcher dFetcher;
        public OrderController() : base()
        {
            this.manager = new OrderManager();
            this.fetcher = new OrderFetcher();
            this.dFetcher = new OrderDetailFetcher();
        }
        [HttpPost]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Retail, AppOpt.Create)]
        public AsmMainDetail<OrderModel, OrderDetailModel> Set(dynamic dataJson)
        {
            string mainStr = (String)dataJson.main;
            string detailStr = (String)dataJson.detail;

            var main = Util.ConvertObjectFromJson<OrderModel>(mainStr);

            LogHelper.Debug(this.GetType(), String.Format("SET:[RQS|{2}]{0}|[DETAIL]{1}", Util.ConvertToJson(main), dataJson, RequestIp));
            var details = Util.ConvertArrayFromJson<OrderDetailModel>(detailStr);

            if (main == null||details.Count()==0)
            {
                DBHelper.Commit(false);
                LogHelper.Err(this.GetType(), String.Format("SET:从{0}中接收到空的参数", RequestIp));
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                var errResponse = new AsmMainDetail<OrderModel, OrderDetailModel>() { Message = "传入的参数不能为空", Result = AmsCode.ArgNotAccept };
                LogHelper.Debug(this.GetType(), String.Format("SET:[RSP|{1}]{0}", Util.ConvertToJson(errResponse), RequestIp));
                return errResponse;
            }
            foreach (var item in details)
            {
                item.OrderId = main.AutoId;
            }
            var qtyColumn = from item in details select item.Qty;

            main.Info = String.Format("本订单包括[{0}]等[{1}]种产品共{2}件", details.First().ProductionName, details.Count(), qtyColumn.Sum()); 
            var result = manager.Set(main, details);
            LogHelper.Debug(this.GetType(), String.Format("SET:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            DBHelper.Commit( result.Result);
            return result;
        }
        [HttpPost]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Retail, AppOpt.Delete)]
        public AsmObject<bool> Del(OrderModel model)
        {
            LogHelper.Debug(this.GetType(), String.Format("DEL:[RQS|{1}]{0}", Util.ConvertToJson(model), RequestIp));
            if (model == null)
            {
                DBHelper.Commit( false);
                LogHelper.Err(this.GetType(), String.Format("DEL:从{0}中接收到空的参数", RequestIp));
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return new AsmObject<bool>() { Data = false, Message = "传入的参数不能为空", Result = AmsCode.ArgNotAccept };
            }
            AsmObject<bool> result = manager.Delete(model);
            DBHelper.Commit( result.Result);
            LogHelper.Debug(this.GetType(), String.Format("DEL:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            return result;
        }
        [HttpPost]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Retail, AppOpt.Delete)]
        public AsmArray<Int32> BulkDel(dynamic jsonOrderModel)
        {
            LogHelper.Debug(this.GetType(), String.Format("BULKDEL:[RQS|{1}]{0}", jsonOrderModel, RequestIp));
            var models = Util.ConvertArrayFromJson<OrderModel>((String)jsonOrderModel.data);
            if (models == null)
            {
                LogHelper.Err(this.GetType(), String.Format("BULKDEL:从{0}中接收到空的参数", RequestIp));
                Response.StatusCode = (Int32)HttpStatusCode.BadRequest;
                var errResponse = new AsmArray<Int32>() { Data = new List<Int32>(), Message = "传入的参数不能为空", Result = AmsCode.ArgNotAccept };
                LogHelper.Debug(this.GetType(), String.Format("BULKDEL:[RSP|{1}]{0}", Util.ConvertToJson(errResponse), RequestIp));
                return errResponse;
            }
            int faild = models.Count();
            var del = new List<Int32>();
            StringBuilder sb = new StringBuilder();
            foreach (var model in models)
            {
                var eff = manager.Delete(model);
                if (eff.Result != 0)
                {
                    sb.AppendFormat("{0}:{1}\r\n", model.AutoId, eff.Message);
                }
                else
                {
                    del.Add(model.AutoId);
                    faild--;
                }
            }
            DBHelper.Commit(true);
            var succResponse = new AsmArray<Int32>() { Data = del, Message = "共有" + (models.Count() - faild) + "笔资料删除成功", Result = AmsCode.Succ };
            LogHelper.Debug(this.GetType(), String.Format("BULKDEL:[RSP|{1}]{0}", Util.ConvertToJson(succResponse), RequestIp));
            return succResponse;
        }
        [HttpPost]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Retail, AppOpt.Approve)]
        public AsmMainDetail<OrderModel, OrderDetailModel> Approve(OrderModel model)
        {
            Console.WriteLine("test");
            LogHelper.Debug(this.GetType(), String.Format("APPROVE:[RQS|{1}]{0}", Util.ConvertToJson(model), RequestIp));
            if (model == null)
            {
                DBHelper.Commit( false);
                LogHelper.Err(this.GetType(), String.Format("APPROVE:从{0}中接收到空的参数", RequestIp));
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return new AsmMainDetail<OrderModel, OrderDetailModel>() { Data = null, Message = "传入的参数不能为空", Result = AmsCode.ArgNotAccept };
            }
            AsmObject<bool> success = manager.Approve(model);
            AsmMainDetail<OrderModel, OrderDetailModel> result = null;
            if (success.Result == AmsCode.Succ)
            {
                result = Get(model.AutoId);
            }
            else
            {
                result = new AsmMainDetail<OrderModel, OrderDetailModel>() { Data = null, Detail = null, Message = success.Message, Result = success.Result };
            }
            DBHelper.Commit(success.Result);
            LogHelper.Debug(this.GetType(), String.Format("APPROVE:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            return result;
        }
        [HttpPost]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Center, AppOpt.UnApprove)]
        public AsmObject<bool> UnApprove(OrderModel model)
        {
            LogHelper.Debug(this.GetType(), String.Format("UNAPPROVE:[RQS|{1}]{0}", Util.ConvertToJson(model), RequestIp));
            if (model == null)
            {
                DBHelper.Commit( false);
                LogHelper.Err(this.GetType(), String.Format("UNAPPROVE:从{0}中接收到空的参数", RequestIp));
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return new AsmObject<bool>() { Data = false, Message = "传入的参数不能为空", Result = AmsCode.ArgNotAccept };
            }
            AsmObject<bool> result = manager.UnApprove(model);
            DBHelper.Commit( result.Result);
            LogHelper.Debug(this.GetType(), String.Format("UNAPPROVE:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            return result;
        }
        [HttpGet]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Retail, AppOpt.Exec)]
        public AsmArray<OrderModel> List(string conditions, int pos, int size)
        {
            LogHelper.Debug(this.GetType(), String.Format("LIST:[RQS|{1}]{0}", conditions, RequestIp));
            int cnt = 0;
            var ls = fetcher.List(Util.ConvertArrayFromJson<Condition>(conditions), pos, size, out cnt);
            DBHelper.Commit( true);
            var result = new AsmArray<OrderModel>() { Data = ls, Message = "操作成功", Result = AmsCode.Succ, Cnt = cnt };
            LogHelper.Debug(this.GetType(), String.Format("LIST:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            return result;
        }

        [HttpGet]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Retail, AppOpt.Exec)]
        public AsmArray<OrderModel> ListByRetail(int retail, int pos, int size)
        {
            LogHelper.Debug(this.GetType(), String.Format("LISTBYRETAIL:[RQS|{1}]{0}", Util.ConvertToJson(retail), RequestIp));
            int cnt = 0;
            var ls = fetcher.ListByRetail(retail, pos, size, out cnt);
            DBHelper.Commit( true);
            var result = new AsmArray<OrderModel>() { Data = ls, Message = "操作成功", Result = AmsCode.Succ, Cnt = cnt };
            LogHelper.Debug(this.GetType(), String.Format("LISTBYRETAIL:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            return result;
        }

        [HttpGet]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Retail, AppOpt.Exec)]
        public AsmMainDetail<OrderModel, OrderDetailModel> Get(int id)
        {
            LogHelper.Debug(this.GetType(), String.Format("GET:[RQS|{1}]{0}", Util.ConvertToJson(id), RequestIp));
            var main = fetcher.Get(id);
            if (main == null)
            {
                var errResponse = new AsmMainDetail<OrderModel, OrderDetailModel> { Data = main, Detail = null, Message = "找不到数据", Result = AmsCode.DataNotFound };
                DBHelper.Commit( false);
                LogHelper.Debug(this.GetType(), String.Format("GET:[RSP|{1}]{0}", Util.ConvertToJson(errResponse), RequestIp));
                return errResponse;
            }
            var detail = dFetcher.ListDetail(id);
            DBHelper.Commit( true);
            var result = new AsmMainDetail<OrderModel, OrderDetailModel> { Data = main, Detail = detail, Message = "操作成功", Result = AmsCode.Succ };
            LogHelper.Debug(this.GetType(), String.Format("GET:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            return result;
        }

        [HttpGet]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Retail, AppOpt.Exec)]
        public AsmArray<OrderDetailModel> ListDetail(int id)
        {
            LogHelper.Debug(this.GetType(), String.Format("LISTDETAIL:[RQS|{1}]{0}", id, RequestIp));
            var detail = dFetcher.ListDetail(id);
            DBHelper.Commit(true);
            var result = new AsmArray<OrderDetailModel> { Data = detail, Message = "操作成功", Result = AmsCode.Succ };
            LogHelper.Debug(this.GetType(), String.Format("LISTDETAIL:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
            return result;
        }

        [HttpPost]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Retail, AppOpt.Approve)]
        public AsmObject<String> Handle(dynamic jsonOrderModel)
        {
            LogHelper.Debug(this.GetType(), String.Format("CONFIRM:[RQS|{1}]{0}", Util.ConvertToJson(jsonOrderModel), RequestIp));
            if (jsonOrderModel == null)
            {
                DBHelper.Commit(false);
                LogHelper.Err(this.GetType(), String.Format("CONFIRM:从{0}中接收到空的参数", RequestIp));
                Response.StatusCode = (int)HttpStatusCode.Accepted;
                return new AsmObject<String>() { Data = "传入的参数不能为空", Message = "传入的参数不能为空", Result = AmsCode.ArgNotAccept };
            }
            try
            {
                string mainStr = (String)jsonOrderModel.AutoId;
                //string detailStr = (String)jsonOrderModel.Detail;

                int mainId = 0;
                Int32.TryParse(mainStr, out mainId);
                //var detail = Util.ConvertArrayFromJson<ConfirmDetail>(detailStr);

                var main = fetcher.Get(mainId);
                if (main == null )
                {
                    DBHelper.Commit(false);
                    Response.StatusCode = (int)HttpStatusCode.Accepted;
                    return new AsmObject<String>() { Data = "找不到该单据", Message = "找不到该单据", Result = AmsCode.DataNotFound };
                }
                if (main.Status != (int)AgencyManagerSystem.Common.StatusCode.Open)
                {
                    DBHelper.Commit(false);
                    Response.StatusCode = (int)HttpStatusCode.Accepted;
                    return new AsmObject<String>() { Data = "单据状态不正确", Message = "单据状态不正确", Result = AmsCode.DataNotFound };
                }
                main.Status = (int)AgencyManagerSystem.Common.StatusCode.Pushed;
                string message;
                int result = OrderUpdater.GetMainUpdater().Save(main, out message);
                if (result == 0)
                {
                    DBHelper.Commit(false);
                    return new AsmObject<String>() { Data = message, Message = message, Result = AmsCode.DataNotFound };
                }
                /*
                foreach (var item in jsonOrderModel.Detail)
                {
                    var record = dFetcher.Get((int)item.DetailId);
                    if (record == null)
                    {
                        DBHelper.Commit(false);
                        return new AsmObject<String>() { Data = "单据状态不正确", Message = "单据状态不正确", Result = AmsCode.DataNotFound };
                    }
                    record.Price = (decimal)item.Price;
                    record.Amount = (decimal)item.Price * record.Qty;

                    if (OrderUpdater.GetDetailUpdater().Save(record, out message) == 0)
                    {
                        DBHelper.Commit(false);
                        return new AsmObject<String>() { Data = message, Message = message, Result = AmsCode.DataNotFound };
                    }
                }
                */
                DBHelper.Commit(true);
                LogHelper.Debug(this.GetType(), String.Format("CONFIRM:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
                return new AsmObject<String>() { Data = "作业成功", Message = "作业成功", Result = AmsCode.Succ };
            }
            catch(Exception ex)
            {
                DBHelper.Commit(false);
                return new AsmObject<String>() { Data = ex.Message, Message = ex.Message, Result = AmsCode.InnError };
            }
        }

        [HttpPost]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Retail, AppOpt.Approve)]
        public AsmObject<String> Confirm(dynamic jsonOrderModel)
        {
            LogHelper.Debug(this.GetType(), String.Format("CONFIRM:[RQS|{1}]{0}", Util.ConvertToJson(jsonOrderModel), RequestIp));
            if (jsonOrderModel == null)
            {
                DBHelper.Commit(false);
                LogHelper.Err(this.GetType(), String.Format("CONFIRM:从{0}中接收到空的参数", RequestIp));
                Response.StatusCode = (int)HttpStatusCode.Accepted;
                return new AsmObject<String>() { Data = "传入的参数不能为空", Message = "传入的参数不能为空", Result = AmsCode.ArgNotAccept };
            }
            try
            {
                string mainStr = (String)jsonOrderModel.AutoId;
                //string detailStr = (String)jsonOrderModel.Detail;

                int mainId = 0;
                Int32.TryParse(mainStr, out mainId);
                //var detail = Util.ConvertArrayFromJson<ConfirmDetail>(detailStr);

                var main = fetcher.Get(mainId);
                if (main == null || main.Status != (int)AgencyManagerSystem.Common.StatusCode.Pushed)
                {
                    DBHelper.Commit(false);
                    Response.StatusCode = (int)HttpStatusCode.Accepted;
                    return new AsmObject<String>() { Data = "单据状态不正确", Message = "单据状态不正确", Result = AmsCode.DataNotFound };
                }
                main.Status = (int)AgencyManagerSystem.Common.StatusCode.Confirm;
                string message;
                int result = OrderUpdater.GetMainUpdater().Save(main, out message);
                if (result == 0)
                {
                    DBHelper.Commit(false);
                    return new AsmObject<String>() { Data = message, Message = message, Result = AmsCode.DataNotFound };
                }
                DBHelper.Commit(true);
                LogHelper.Debug(this.GetType(), String.Format("CONFIRM:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
                return new AsmObject<String>() { Data = "作业成功", Message = "作业成功", Result = AmsCode.Succ };
            }
            catch (Exception ex)
            {
                DBHelper.Commit(false);
                return new AsmObject<String>() { Data = ex.Message, Message = ex.Message, Result = AmsCode.InnError };
            }
        }

        [HttpPost]
        [RoleFlagAuthorizeAttribute(PolicyDomain.Retail, AppOpt.Approve)]
        public AsmObject<String> Finish(dynamic jsonOrderModel)
        {
            LogHelper.Debug(this.GetType(), String.Format("CONFIRM:[RQS|{1}]{0}", Util.ConvertToJson(jsonOrderModel), RequestIp));
            if (jsonOrderModel == null)
            {
                DBHelper.Commit(false);
                LogHelper.Err(this.GetType(), String.Format("CONFIRM:从{0}中接收到空的参数", RequestIp));
                Response.StatusCode = (int)HttpStatusCode.Accepted;
                return new AsmObject<String>() { Data = "传入的参数不能为空", Message = "传入的参数不能为空", Result = AmsCode.ArgNotAccept };
            }
            try
            {
                string mainStr = (String)jsonOrderModel.AutoId;
                //string detailStr = (String)jsonOrderModel.Detail;

                int mainId = 0;
                Int32.TryParse(mainStr, out mainId);
                //var detail = Util.ConvertArrayFromJson<ConfirmDetail>(detailStr);

                var main = fetcher.Get(mainId);
                if (main == null || main.Status != (int)AgencyManagerSystem.Common.StatusCode.Confirm)
                {
                    DBHelper.Commit(false);
                    Response.StatusCode = (int)HttpStatusCode.Accepted;
                    return new AsmObject<String>() { Data = "单据状态不正确", Message = "单据状态不正确", Result = AmsCode.DataNotFound };
                }
                main.Status = (int)AgencyManagerSystem.Common.StatusCode.Closed;
                string message;
                int result = OrderUpdater.GetMainUpdater().Save(main, out message);
                if (result == 0)
                {
                    DBHelper.Commit(false);
                    return new AsmObject<String>() { Data = message, Message = message, Result = AmsCode.DataNotFound };
                }
                DBHelper.Commit(true);
                LogHelper.Debug(this.GetType(), String.Format("CONFIRM:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));
                return new AsmObject<String>() { Data = "作业成功", Message = "作业成功", Result = AmsCode.Succ };
            }
            catch (Exception ex)
            {
                DBHelper.Commit(false);
                return new AsmObject<String>() { Data = ex.Message, Message = ex.Message, Result = AmsCode.InnError };
            }
        }
    }
}